package org.sanguine.study.hometasks.second;

import java.io.File;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.sanguine.study.hometasks.first.TaskWorker;

public class Task2 implements TaskWorker {
	private PrintWriter out;
	private String directoryName;
	private File directory;
	private List<File> directoryList = new ArrayList<>();

	public static void main(String[] args) {
		TaskWorker task = new Task2();
		
		if (task.setUp(null, null, args)) {
			task.doTask();
		} else {
			System.err.println("Setup failed");
		}
	}

	private void printUsage() {
		System.err.println("USAGE: java -jar Task2.jar 'dirName'");
	}

	@Override
	public boolean setUp(Reader in, PrintWriter out, String[] args) {
		if (args == null || args.length < 1) {
			printUsage();
			return false;
		}
		directoryName = args[0];
		this.out = out;
		directory = new File(directoryName);
		if (directory.isDirectory()) return true;
		
		System.err.printf("%s is not directory or does not exist%n", directoryName);
		directory = null;
		return false;
	}

	@Override
	public void doTask() {
		if (directory == null || out == null) return;
		
		directoryList.addAll(getDirectoryList(directory));
		directoryList.remove(directory); //delete root of directory tree from content 
		
		printList();
	}

	private void printList() {
		if (out == null || directoryList == null) return;
		out.printf("Content of directory %s:%n", directoryName);
		
		int startDepth = getDepth(directory);
		for (File fl : directoryList) {
			for (int i = 0; i < getDepth(fl) - startDepth; i++) out.print("\t");
			out.println(fl.getName());
		}
	}

	private Collection<File> getDirectoryList(File root) {
		if (root == null) return Collections.emptyList();
		if (root.isFile()) return Collections.singletonList(root);

		List<File> files = new ArrayList<>();
		files.add(root);
		
		File[] content = root.listFiles();
		for (File file : content) {
			files.addAll(getDirectoryList(file));
		}

		return files;
	}
	
	private int getDepth(File file) {
		if (file == null) return 0;
		
		int depth = 0;
		File fl = file;
		while ((fl = fl.getParentFile()) != null) depth++;
		return depth;
	}
}
